import { h, createVNode, ref } from 'vue';
import { Modal, message, RadioGroup } from 'ant-design-vue';
import { uploadFileByPolicy, moveFileItem } from '@/api/bimface/fileItems';
import { updateNewVersionByPolicy } from '@/api/bimface/files';
import { getTranslateStatus, translate } from '@/api/bimface/translate';

const projectId = localStorage.getItem('bimface_project_id')!;
const texture = ref<boolean>(true);
export function useFileManager() {
  /**
   * 上传模型
   * @param modelName 模型名称
   * @param parentPath 文件夹路径
   * @param file 文件
   * @param callback 上传进度回调函数
   * @returns 结果数据
   */
  async function uploadBimModel(
    modelName: string,
    parentPath: string,
    file: File,
    callback?: (progress: number) => void,
  ) {
    const res = await uploadFileByPolicy(
      projectId,
      {
        name: modelName,
        parentPath: parentPath,
      },
      file,
      (e) => callback && callback(parseInt(e.progress * 100)),
    );
    return res.data;
  }

  /**
   * 更新模型
   * @param fileItemId 文件项id
   * @param modelName 模型名称
   * @param file 文件
   * @param callback 上传进度回调函数
   * @returns 结果数据
   */
  async function updateBimModel(
    fileItemId: string,
    modelName: string,
    file: File,
    callback: (progress: number) => void,
  ) {
    const res = await updateNewVersionByPolicy(
      projectId,
      { fileItemId, name: modelName },
      file,
      (e) => callback(parseInt(e.progress * 100)),
    );
    return res.data;
  }

  /**
   * 移动文件到回收站
   * @param fileItemIds 文件项id列表
   * @returns 结果数据
   */
  async function moveBimFileToRecycleBin(fileItemIds: string[]) {
    const res = await moveFileItem(projectId, {
      fileItemIds: fileItemIds,
      targetParentPath: '/回收文件',
    });
    return res.data;
  }

  /**
   * 获取模型轻量化转换状态
   * @param fileId 模型文件id
   * @param successCallback 成功回调
   */
  async function getBimFileTranslateStatus(fileId, successCallback) {
    const res = await getTranslateStatus({ fileId });
    if (!res.data) {
      translateModel(fileId);
      return;
    }
    if (res.data.status === 'processing') {
      message.info('模型轻量化中，请稍候再试');
      return;
    }
    if (res.data.status === 'success') {
      successCallback();
    }
  }

  async function translateModel(fileId) {
    Modal.confirm({
      title: '提示',
      content: h('div', {}, [
        h('p', '模型暂未轻量化，是否要发起轻量化转换?'),
        h('p', '本次模型轻量化转换将消耗【7】活动点'),
        createVNode(RadioGroup, {
          options: [
            { label: '着色(高性能)模式', value: true },
            { label: '真实模式', value: false },
          ],
          value: texture,
          'onUpdate:value': ($event) => {
            texture.value = $event;
          },
        }),
      ]),

      centered: true,
      onOk() {
        const translateRequestData = {
          source: {
            fileId: fileId,
            compressed: false,
          },
          config: {
            toBimtiles: true,
            text: texture.value,
          },
        };
        translate(translateRequestData)
          .then((res) => {
            if (res.data.status === 'success') {
              message.success('成功发起转换，请耐心等待');
            } else {
              message.warn('轻量化资源已用完，请联系管理员');
            }
          })
          .catch((e) => {
            message.error('发起转换失败');
            console.error('发起转换失败：', e);
          });
      },
    });
  }

  return {
    uploadBimModel,
    updateBimModel,
    moveBimFileToRecycleBin,
    getBimFileTranslateStatus,
  };
}
